//
// Created by 33145 on 2023/6/6.
//

#ifndef ROCKET_TCP_CLIENT_H
#define ROCKET_TCP_CLIENT_H

#include "tcp_connection.h"
#include "../coder/abstract_protocol.h"

namespace rocket {

  class TCPClient {
  public:

    typedef std::shared_ptr<TCPClient> ptr;

    explicit TCPClient(const NetAddr::ptr& peer_addr);
    ~TCPClient();

    void connect(const std::function<void()>& done);
    void writeMessage(const AbstractProtocol::ptr& message, const std::function<void(AbstractProtocol::ptr)>& done);
    void readMessage(const std::string& msg_id, std::function<void(AbstractProtocol::ptr)> done);

    void stop();
    int getConnectErrorCode();
    std::string getConnectErrorInfo();
    NetAddr::ptr getPeerAddr();
    NetAddr::ptr getLocalAddr();
    void initLocalAddr();
    void addTimerEvent(const TimerEvent::ptr& timer_event);

  private:
    NetAddr::ptr _peer_addr;
    NetAddr::ptr _local_addr;

    EventLoop::ptr _event_loop {nullptr};

    FdEvent::ptr _fd_event {nullptr};
    TCPConnection::ptr _connection;
    std::string _connect_error_info;

    int _fd {-1};
    int _connect_error_code {0};
  };

}

#endif //ROCKET_TCP_CLIENT_H
